package top.zhangjianyong.tools.canteen;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.constant.CanteenAccount;
import top.zhangjianyong.tools.entity.Vegetable;
import top.zhangjianyong.tools.utils.CanteenApiUtil;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author ： zhangjianyong
 * @date ： 2023/2/22 3:04 PM
 */
@Slf4j
@Data
@Component
public class CanteenCheckHandler {
    @Value("${canteen.timeout}")
    private Integer timeout;
    /**
     * 一天的餐大于多少个表示当天的餐已全部放出
     */
    @Value("${canteen.menus}")
    private Integer menus;
    @Value("${canteen.url}")
    private String startUrl;

    private Set<String> orderedUrl = new HashSet<>();

    /**
     * @return false超时；true餐点已放出
     */
    public boolean process() throws InterruptedException {
        LocalDateTime now = LocalDateTime.now();
        int dayOfWeek = now.getDayOfWeek().getValue();
        LocalDateTime endTime = now.plusMinutes(timeout);
        CanteenAccount account = CanteenAccount.getOneByDayOfWeek(dayOfWeek);
        if (account == null) {
            log.info("当天没有需要点餐账号");
            return false;
        }
        //检查是否可以点餐
        Boolean check = doCheck(account.userName, account.password, endTime);
        return check;
    }

    /**
     * 检查是否已放出餐
     *
     * @param userName 用户名
     * @param password 密码
     * @param endTime  超时时间
     * @return
     * @throws InterruptedException
     */
    public Boolean doCheck(String userName, String password, LocalDateTime endTime) throws InterruptedException {
        //通用前置处理
        CanteenApiUtil.loginForCanteen(userName,password);
        //获取可点日期
        List<String> menuUris = CanteenApiUtil.getMenuUris();

        //检查是否可以点餐
        boolean flag = true;
        CanteenApiUtil.addMessage("[检查点餐] 开始检查");
        while (flag) {
            log.info("[检查] 进入放餐检查");
            for (String menuUri : menuUris) {
                List<Vegetable> menu = CanteenApiUtil.getMenu(menuUri, false);
                if (CollectionUtil.isNotEmpty(menu)
                        && menu.size() >= menus
                        && !orderedUrl.contains(menuUri)) {
                    orderedUrl.add(menuUri);
                    flag = false;
                    break;
                }
            }
            if (LocalDateTime.now().isAfter(endTime)) {
                CanteenApiUtil.addMessage("[检查超时] 当前未开放点餐");
                CanteenApiUtil.addMessage("[重新启动] 请点击链接重新启动: {}",
                        startUrl);
                return false;
            }
        }
        return true;
    }
}
